package com.ruoyi.activiti.controller;

import com.ruoyi.activiti.domain.StandingBookVo;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.activiti.service.StandingBookService;
import com.ruoyi.activiti.utils.ChineseToPinyinUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.BaseResult;
import com.ruoyi.util.ResultEnum;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.activiti.engine.task.Task;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author zeo
 * @explain 成本中心结算填报
 * @date 2020/10/14 14:03
 */
@Controller
@RequestMapping("/settlement")
public class StandingBookController extends BaseController {

    @Autowired
    StandingBookService standingBookService;
    @Autowired
    ISysDeptService deptService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IProcessService processService;

    private String prefix = "standingbook";

    @GetMapping()
    public String StandingBook(ModelMap mmap) {
        mmap.put("currentUser", ShiroUtils.getSysUser());
        return prefix + "/standingBook";
    }

    /**
     * 查询周报业务列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StandingBookVo standingBookVo) {
        if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
            standingBookVo.setCreateBy(ShiroUtils.getLoginName());
        }
        startPage();
        List<StandingBookVo> list = standingBookService.selectStandingBookList(standingBookVo);
        return getDataTable(list);
    }

    /**
     * 新增周报业务
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("user", user);
        return prefix + "/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StandingBookVo standingBookVo) {
        Long userId = ShiroUtils.getUserId();
        if (SysUser.isAdmin(userId)) {
            return error("提交申请失败：不允许管理员提交申请！");
        }
        return toAjax(standingBookService.insertStandingBook(standingBookVo));
    }

    /**
     * 修改周报业务
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        SysUser user = ShiroUtils.getSysUser();
        mmap.put("user", user);
        StandingBookVo standingBookVo = standingBookService.selectStandingBookById(id);
        mmap.put("standingBookVo", standingBookVo);
        return prefix + "/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StandingBookVo standingBookVo) {
        return toAjax(standingBookService.updateStandingBook(standingBookVo));
    }

    @RequestMapping("/edit.ajax")
    @ResponseBody
    public BaseResult editAjax(StandingBookVo standingBookVo){
        if(standingBookService.updateStandingBook(standingBookVo) > 0){
            return BaseResult.build(ResultEnum.SUCCESS);
        }else{
            return BaseResult.build(ResultEnum.FAILURE);
        }
    }

    @RequestMapping("/createNumber")
    @ResponseBody
    public String createNumber(StandingBookVo standingBookVo) {
        String maxNumber = standingBookService.maxNumber(standingBookVo);
        if (maxNumber == null) {
            maxNumber = "0001";
        } else if (maxNumber.length() == 1) {
            maxNumber = "000" + maxNumber;
        } else if (maxNumber.length() == 2) {
            maxNumber = "00" + maxNumber;
        } else if (maxNumber.length() == 3) {
            maxNumber = "0" + maxNumber;
        }
        String proName = ChineseToPinyinUtil.pinyinInitials(standingBookVo.getProName());
        return standingBookVo.getCompTitle() + "-" + proName + "-" + maxNumber;
    }


    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(standingBookService.remove(ids));
    }
    /**
     * 提交申请
     */
    @PostMapping("/submitApply")
    @ResponseBody
    public AjaxResult submitApply(String id) {
        StandingBookVo standingBookVo = standingBookService.selectStandingBookById(id);
        String applyUserId = ShiroUtils.getLoginName();
        standingBookService.submitApply(standingBookVo, applyUserId, "settlement", new HashMap<>());
        return success();
    }

    /**
     * 加载审批弹窗
     *
     * @param taskId
     * @param mmap
     * @return
     */
    @GetMapping("/showVerifyDialog/{taskId}")
    public String showVerifyDialog(@PathVariable("taskId") String taskId, ModelMap mmap) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        StandingBookVo standingBookVo = standingBookService.selectStandingBookById(processInstance.getBusinessKey());
        String createByName = sysUserService.selectUserByLoginName(standingBookVo.getCreateBy()).getUserName();
        mmap.put("createByName", createByName);
        mmap.put("standingBookVo", standingBookVo);
        mmap.put("taskId", taskId);
        String verifyName = task.getTaskDefinitionKey().substring(0, 1).toUpperCase() + task.getTaskDefinitionKey().substring(1);
        if (verifyName.equals("Distribute")) {
            //分发岗位传入初审人员名单
            mmap.put("csUserList", sysUserService.getUserByRoleName("台账初审人员"));
        }
        return prefix + "/task" + verifyName;
    }

    /**
     * 完成任务
     *
     * @return
     */
    @RequestMapping(value = "/complete/{taskId}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public AjaxResult complete(@PathVariable("taskId") String taskId, @RequestParam(value = "saveEntity", required = false) String saveEntity,
                               @ModelAttribute("preloadSettlement") StandingBookVo standingBookVo, HttpServletRequest request, String p_B_isPreliminary, String csry) {
        boolean saveEntityBoolean = BooleanUtils.toBoolean(saveEntity);
        Map map = new HashMap<>();
        map.put("type", "settlement");
        if(csry != null && !csry.equals("")){
            map.put("csry", sysUserService.selectUserById(Long.parseLong(csry)).getLoginName());
        }
        processService.completeCurrency(taskId, standingBookVo.getInstanceId(), standingBookVo.getProName(), standingBookVo.getAuditContent(), "settlement", new HashMap<String, Object>(), request, map);
        if (saveEntityBoolean) {
            if(p_B_isPreliminary != null && "false".equals(p_B_isPreliminary)){
                standingBookVo.setRectifyReason(standingBookVo.getComment());
                standingBookVo.setRectifyTime(new Date());
            }
            standingBookService.updateStandingBook(standingBookVo);
        }
        /*
        if (p_B_deptLeaderApproved) {
            //最后一个领导审核完并同意即归档
            bizWeeklyService.insertGdWeekly(bizWeeklyVo);
        }
        */

        return success("任务已完成");
    }


    /**
     * 自动绑定页面字段
     */
    @ModelAttribute("preloadSettlement")
    public StandingBookVo getSettlement(@RequestParam(value = "id", required = false) String id, HttpSession session) {
        if (id != null) {
            return standingBookService.selectStandingBookById(id);
        }
        return new StandingBookVo();
    }
}
